using FreeRedis;
using Digitalmes.Common.Utils;

namespace Digitalmes.Common.Cache;

/// <summary>
/// redis 缓存。
/// </summary>
public sealed class RedisService
{
    /// <summary>
    /// redis 客户端
    /// </summary>
    public static RedisClient Cli => new(AppUtils.Configuration["Cache:Redis"]);

    /// <summary>
    /// redis 服务实例
    /// </summary>
    public static readonly RedisService Instance;

    static RedisService()
    {
        Instance = new RedisService();
    }

    /// <summary>
    /// 查询 Redis 数据。
    /// </summary>
    /// <param name="redisKey"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T? Get<T>(string redisKey) where T : class, new()
    {
        var redisStr = Cli.Get(redisKey);
        return !string.IsNullOrEmpty(redisStr) ? JsonSerializer.Deserialize<T>(redisStr) : null;
    }

    /// <summary>
    /// 查询 Redis 数据。
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public string? GetString(string redisKey)
    {
        return Cli.Get(redisKey);
    }

    /// <summary>
    /// 设置 redis 数据。
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public void SetJson<T>(string redisKey, T value)
    {
        Cli.Set(redisKey, JsonSerializer.Serialize(value));
    }

    /// <summary>
    /// 设置 redis 数据。
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="value"></param>
    public void SetString(string redisKey, string value)
    {
        Cli.Set(redisKey, value);
    }

    /// <summary>
    /// 移除指定的健。
    /// </summary>
    /// <param name="redisKey"></param>
    public void Del(string redisKey)
    {
        Cli.Del(redisKey);
    }
}
